package xcmg.device.web.warehouse;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import xcmg.device.dao.entity.PriMaterialsDO;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.entity.warehouse.WarehouseDO;
import xcmg.device.dao.entity.warehouse.allot.RegionAllotPlanDO;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.infra.AuthCode;
import xcmg.device.infra.BasicController;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.annotation.ExternalApiRequest;
import xcmg.device.infra.enums.ReginAllotPlanStatusEnum;
import xcmg.device.service.ExternalParamCheckService;
import xcmg.device.service.warehouse.allot.RegionAllotPlanDetailService;
import xcmg.device.service.warehouse.allot.RegionAllotPlanService;
import xcmg.device.service.warehouse.allot.RegionAllotService;
import xcmg.device.service.warehouse.allot.vo.RegionAllotPlanDetailVO;
import xcmg.device.service.warehouse.allot.vo.RegionAllotPlanVO;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;

import java.util.ArrayList;
import java.util.List;

/**
 * 区域调拨计划 Controller 实现类
 */
@Slf4j
@RestController
@RequestMapping("/regionAllotPlan")
public class RegionAllotPlanController extends BasicController {

    @Autowired
    private RegionAllotPlanService regionAllotPlanService;

    @Autowired
    private RegionAllotPlanDetailService regionAllotPlanDetailService;

    @Autowired
    private CompanyInfoMapper companyInfoMapper;
    @Autowired
    private RegionAllotService regionAllotService;
    @Autowired
    private ExternalParamCheckService externalParamCheckService;

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ApiOperation(value = "区域调拨计划表分页列表信息")
    @FastMappingInfo(needLogin = true)
    public ActionResult<PageInfo<RegionAllotPlanVO>> list(@RequestBody SearchCommonVO<RegionAllotPlanVO> condition) throws Exception {
        RegionAllotPlanVO regionAllotVO = condition.getFilters();
        if (regionAllotVO == null) {
            regionAllotVO = new RegionAllotPlanVO();
        }
        regionAllotVO.setOrgId(getOrgId());
        regionAllotVO.setIsDel(0);
        condition.setFilters(regionAllotVO);
        PageCommonVO<RegionAllotPlanVO> pageCommonVO = regionAllotPlanService.list(condition, false,getDeptId());
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/item", method = RequestMethod.GET)
    @ApiOperation(value = "查找单条记录详情")
    @FastMappingInfo(needLogin = true)
    public ActionResult<RegionAllotPlanVO> item(String id) throws Exception {
        return actionValueResult(regionAllotPlanService.queryById(id, getOrgId()));
    }

    @RequestMapping(value = "/itemByNo", method = RequestMethod.GET)
    @ApiOperation(value = "查找单条记录详情")
    @FastMappingInfo(needLogin = true)
    public ActionResult<RegionAllotPlanVO> itemByNo(String allotPlanOrder) throws Exception {
        return actionValueResult(regionAllotPlanService.queryByAllotPlanOrder(allotPlanOrder, getOrgId()));
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "增加区域调拨申请(保存)")
    @FastMappingInfo(needLogin = true, code = AuthCode.RegionAllotPlan.ADD)
    public ActionResult add(@RequestBody RegionAllotPlanVO regionAllotPlanVO) throws Exception {
        if (null == regionAllotPlanVO) {
            return actionResult(ErrorCode.IllegalArument);
        }
        regionAllotPlanVO.setDept(getDeptName());
        regionAllotPlanVO.setDeptId(getDeptId());
        ErrorCode errorCode = regionAllotPlanService.add(regionAllotPlanVO, getUserId(), getOrgId(), ReginAllotPlanStatusEnum.save.getCode());
        return actionResult(errorCode);
    }

    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @ApiOperation(value = "增加区域调拨申请(提交)")
    @FastMappingInfo(needLogin = true, code = AuthCode.RegionAllotPlan.SUBMIT)
    public ActionResult submit(@RequestBody RegionAllotPlanVO regionAllotPlanVO) throws Exception {
        if (null == regionAllotPlanVO) {
            return actionResult(ErrorCode.IllegalArument);
        }
        regionAllotPlanVO.setDept(getDeptName());
        regionAllotPlanVO.setDeptId(getDeptId());
        ErrorCode errorCode = regionAllotPlanService.add(regionAllotPlanVO, getUserId(), getOrgId(), ReginAllotPlanStatusEnum.submit.getCode());
        return actionResult(errorCode);
    }


    @RequestMapping(value = "/manuFinish", method = RequestMethod.POST)
    @ApiOperation("强制完成单据(根据主表)")
    @FastMappingInfo(needLogin = true, code = AuthCode.RegionAllotPlan.END_BILL)
    public ActionResult<String> manuFinish(@RequestBody ArrayList<String> ids) {
        try {
            return actionResult(regionAllotPlanService.manuFinish(ids, getOrgId()));
        } catch (Exception e) {
            return new ActionResult(500, e.getMessage());
        }
    }

    @RequestMapping(value = "/manuFinishByDetailIds", method = RequestMethod.POST)
    @ApiOperation("强制完成单据(根据行记录)")
    @FastMappingInfo(needLogin = true, code = AuthCode.RegionAllotPlan.END_BILL)
    public ActionResult<String> manuFinishByDetailIds(@RequestBody  ArrayList<String> detailIds) {
        try {
            return actionResult(regionAllotPlanService.manuFinishByDetailIds(detailIds, getOrgId()));
        } catch (Exception e) {
            return new ActionResult(500, e.getMessage());
        }
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ApiOperation("删除编辑状态单据(根据主表)")
    @FastMappingInfo(needLogin = true, code = AuthCode.RegionAllotPlan.DEL)
    public ActionResult<String> delete(@RequestBody  ArrayList<String> ids) {
        try {
            return actionResult(regionAllotPlanService.delete(ids, getOrgId()));
        } catch (Exception e) {
            return new ActionResult(500, e.getMessage());
        }
    }


    @RequestMapping(value = "/exportAll", method = RequestMethod.POST)
    @ApiOperation("导出全部区域调拨计划列表")
    @FastMappingInfo(needLogin = true, code = AuthCode.RegionAllotPlan.EXPORT)
    public void exportAll(RegionAllotPlanVO condition) throws Exception {
        condition.setOrgId(getOrgId());
        regionAllotPlanService.exportAll(condition,getDeptId());
    }



    @RequestMapping(value = "/add4External", method = RequestMethod.POST)
    @ApiOperation(value = "区域调拨单外部接口")
    @ExternalApiRequest
    public ActionResult add4External(@RequestBody RegionAllotPlanVO regionAllotPlanVO) throws Exception {
        if (null == regionAllotPlanVO) {
            return actionResult(ErrorCode.IllegalArument);
        }
        CompanyInfoDO companyInfoDO = companyInfoMapper.itemBySap(regionAllotPlanVO.getSapCode());
        if (null == companyInfoDO) {
            return actionResult(ErrorCode.Failure, "sapCode错误");
        }
        //crmOrder重复单号校验
        ActionResult crmOrderDulpCheck = crmOrderDulpCheck(regionAllotPlanVO);
        if(crmOrderDulpCheck != null && successActionResult(crmOrderDulpCheck)){
            return crmOrderDulpCheck;
        }
        //从RegionAllotPlan中获取传入仓库名称，然后查询长裤记录获取仓库编码
        ActionResult actionResult = tjParamHandle(regionAllotPlanVO);
        if(!successActionResult(actionResult)){
            return actionResult;
        }
        return actionValueResult(regionAllotPlanService.add4External(regionAllotPlanVO, "tj-user", companyInfoDO.getOrgId(), ReginAllotPlanStatusEnum.submit.getCode()));
    }


    //判断crmOrder是否已经存在记录，如果存在则返回操作成功，同时返回存在的PMS编号--
    // 这么返回的原因crm调接口大多加在签核流程里面，多次点击触发接口，返回已存在，会影响签核的动作（具体可以问瑞泰-黄远辉）
    //返回null代表流程可以继续往下走，返回code=0表示已经存在数据，直接返回已存在的数据
    private ActionResult crmOrderDulpCheck(RegionAllotPlanVO regionAllotPlanVO) {
        String crmOrder = regionAllotPlanVO.getCrmOrder();
        if(StringUtils.isEmpty(crmOrder)){
            return actionResult(ErrorCode.Failure,"crm订单号不能为空","crm订单号不能为空");
        }
        RegionAllotPlanDO allotPlan = regionAllotPlanService.getAllotPlanByCrmOrder(crmOrder);
        if(allotPlan != null){
            return actionResult(ErrorCode.Success,"CRM单号已存在",allotPlan.getAllotPlanOrder());
        }
        return null;
    }

    /**
     * 塔机请求的时候传过来的是仓库的名称，需要根据仓库的名称查询转换获取仓库的编码
     * @param regionAllotPlanVO
     */
    private ActionResult tjParamHandle(RegionAllotPlanVO regionAllotPlanVO) throws Exception {
        if(regionAllotPlanVO == null){
            return actionResult(ErrorCode.Success);
        }
        String sapCode = regionAllotPlanVO.getSapCode();
        //如果sapCode为空或者不是塔机的则直接返回
        if(StringUtils.isEmpty(sapCode) || !"2130".equals(sapCode)){
            return actionResult(ErrorCode.Success);
        }

        //塔机的特殊处理根据调入仓库入仓库仓库编码==========start==============
        String inWarehouseDesc = regionAllotPlanVO.getInWarehouseDesc();
        if(StringUtils.isEmpty(inWarehouseDesc)){
            return actionResult(ErrorCode.Failure,"入库仓库参数不能为空","入库仓库参数不能为空");
        }
        String orgId = externalParamCheckService.getOrgIdBySapCode(sapCode);
        List<WarehouseDO> inwarehouse = regionAllotService.getWareHousesByOrgAndDescription(orgId, inWarehouseDesc);
        if(inwarehouse.size() < 1){
            return actionResult(ErrorCode.Failure,"入库仓库"+inWarehouseDesc+"无法匹配","入库仓库"+inWarehouseDesc+"无法匹配");
        }
        String inLocal = inwarehouse.get(0).getWarehouseCode();
        regionAllotPlanVO.setInWarehouse(inLocal);

        //主表默认值设定
        //默认类型311
        String moveType = regionAllotPlanVO.getMoveType();
        if(StringUtils.isEmpty(moveType)){
            regionAllotPlanVO.setMoveType("311");
        }
        regionAllotPlanVO.setCreateId("477477706045325312");
        regionAllotPlanVO.setCreateName("接口用户");
        regionAllotPlanVO.setDept("服务部");
        regionAllotPlanVO.setDeptId("455404133906644992");
        regionAllotPlanVO.setDispatcherId("477477706045325312");
        regionAllotPlanVO.setDispatcherName("接口用户");
        //子表默认值设定
        List<RegionAllotPlanDetailVO> detailVOList = regionAllotPlanVO.getDetailVOList();
        for(RegionAllotPlanDetailVO detailVO : detailVOList){
            String materialNo = detailVO.getMaterialNo();
            PriMaterialsDO materialsInfo = externalParamCheckService.getMaterialsInfo(materialNo);
            if(materialsInfo != null){
                //子表单位（unit字段）拼接
                String unit = materialsInfo.getUnit();
                detailVO.setUnit(unit);
                //子表物描述从数据库中获取，如果能查到则覆盖传过来的零件名称参数
                String materialsDes = materialsInfo.getMaterialsDes();
                if(!StringUtils.isEmpty(materialsDes)){
                    detailVO.setMaterialName(materialsDes);
                }
            }
        }
        return actionResult(ErrorCode.Success);
    }


}
